package org.fuys.coder.domain.file.service;

import com.aliyun.oss.OSSClient;
import org.fuys.coder.common.config.AliYunOssConfig;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @projectName: fuys-low-coder
 * @package: org.fuys.coder.domain.file.service
 * @className: AliYunOSSService
 * @author: WangJing
 * @description: 阿里云OSS服务
 * @date: 2024/6/20 20:24
 * @version: 1.0
 */
@Service
public class AliYunOSSService {

    @Resource
    private AliYunOssConfig aliYunOssConfig;

    @Resource
    private IFileService fileService;

    private OSSClient ossClient;

    @PostConstruct
    public void initClient(){
        ossClient=new OSSClient(aliYunOssConfig.getEndpoint(),
                aliYunOssConfig.getAccessKeyId(), aliYunOssConfig.getAccessKeySecret());
    }

    public boolean doesDataExist(String fileKey){
        return ossClient.doesObjectExist(aliYunOssConfig.getBucketName(), fileKey);
    }

    public String buildUrl(Long id,Date ...date){
        //1小时过期时间 如果传递了date对象 按参数来
        final String fileKey = fileService.getFileKey(id);
        Date expirationDate = date.length==0?new Date(new Date().getTime() + 3600 * 1000):date[0];
        return ossClient.generatePresignedUrl(aliYunOssConfig.getBucketName(),
                fileKey, expirationDate).toString();
    }

    public List<String> buildUrl(List<Long> ids,Date ...date){
        Date expirationDate = date.length==0?new Date(new Date().getTime() + 3600 * 1000):date[0];
        final List<String> fileKeys = fileService.getFileKeys(ids);
        if(!ObjectUtils.isEmpty(fileKeys)){
            return fileKeys.stream().map(fileKey -> {
                return ossClient.generatePresignedUrl(aliYunOssConfig.getBucketName(), fileKey, expirationDate)
                        .toString();
            }).collect(Collectors.toList());
        }
        return null;
    }
    @PreDestroy
    public void closeClient(){
        ossClient.shutdown();
    }
}
